/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controladorUploadImagen;

import modeloUploadImagenFull.FileUpload;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author CEBALLOS
 */
public class FileUploadServerFull extends HttpServlet {

    public int i = -1;
    public ArrayList<String> datos = new ArrayList<>();

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException {
        //response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // HttpSession session = request.getSession();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {

            ServletFileUpload upload = new ServletFileUpload();

            try {

                FileItemIterator itr = upload.getItemIterator(request);

                while (itr.hasNext()) {
                    System.out.println("**************" + isMultipart);

                    FileItemStream item = itr.next();

                    if (item.isFormField()) {
                        //  InputStream stream = item.openStream();
                        //do field specific procces
                        //  String fieldName = item.getFieldName();
                        //do file upload specific procces
                        InputStream Archivo = item.openStream();
                        i = i + 1;

                        byte[] b = new byte[Archivo.available()];
                        Archivo.read(b);

                        String value = new String(b);
                        datos.add(i, value);

                    } else {

                        String cedula = datos.get(0);

                        String ruta = getServletContext().getRealPath("");

                        //call method to upload file
                        if (FileUpload.ProcesarArchivo(ruta, item,cedula)) {
                            FileUpload FL = new FileUpload();
                            FL.ProcesarArchivosql(ruta, item, Integer.parseInt(cedula));
                            datos.clear();
                            i = -1;

                            response.setContentType("text/html");
                            
                            out.println("<html>"
                                    + "<head>"
                                    + "<link href=\"css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>"
                                    + "</head>"
                                    + "<body>"
                                    + "<center><p>Registro correcto Presione Enter</p><form action=\"./StudentServlet\" method=\"POST\">  <table>\n"
                                    + "                    <tr>\n"
                                    + "                        <td>Id</td>\n"
                                    + "                        <td><input type=\"text\" name=\"studentId\" size=\"5\"  value=\""+cedula+"\" readonly autocomplete=\"off\"/></td>\n"
                                    + "                    </tr>\n"
                                    + "                   \n"
                                    + "                    <tr>\n"
                                    + "                        <td colspan=\"2\">\n"
                                    + "\n"  
                                    + "                             <input class=\"buttom\" autofocus type=\"submit\" name=\"action\" value=\"Volver\" />\n"
                                    + "\n"
                                    + "                        </td>                \n"
                                    + "                    </tr>            \n"
                                    + "                </table>   </form></center></body></html>");

                        /*   out.println("<script type=\"text/javascript\">");
                            out.println("window.onload = function myFunction()");
                            out.println("{");
                            out.println("alert('Correcto Usuario Agregado')");
                            out.println("window.location.href='/crudSearchJsp_conImagen/studentinfo_1.jsp';");
                                // out.println("window.location.href='/crudSearchJsp_conImagen/StudentServlet?action=studentId="+cedula+"';");

                            out.println("}");
                            out.println("</script>");*/

                        } else {

                            datos.clear();
                            i = -1;

                            // String valor = request.getParameter("nombres");
                            //session.setAttribute("error", "No se envio el parametro de busqueda!!!" + valor); // request.getRequestDispatcher("/imagenget/faces/index.xhtml").forward(request, response);
                            response.getWriter().println("archivo no subido, faltan campos");
                            // String url = response.encodeRedirectURL("/imagenget/faces/index.xhtml");
                            // response.sendRedirect(url);
                        }

                    }

                }
            } finally {
                //response.getWriter().println("finally");

                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(FileUploadServerFull.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(FileUploadServerFull.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private boolean isNumeric(String cedula) {

        try {
            Integer.parseInt(cedula);
            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }

    }
}
